package com.lemon.smartsafetynew.ui.fragment.record;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.entity.common.CommonBo;
import com.lemon.smartsafetynew.entity.event.common.DataEvent;
import com.lemon.smartsafetynew.ui.activity.hidden.SafeHiddenDangerSearchActivity;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafetynew.entity.event.common.ViewEvent;
import com.lemon.smartsafetynew.entity.record.GridInfoDo;
import com.lemon.smartsafetynew.net.services.RecordServices;
import com.lemon.smartsafetynew.ui.activity.record.RecordCompanyListActivity;
import com.lemon.smartsafetynew.ui.adapter.record.RecordGridListAdapter;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;
import com.lemon.smartsafetynew.util.record.RecordUtils;
import com.lemon.smartsafetynew.util.user.AccountUtil;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 网格列表
 * Created by Andrew on 2018/1/10.
 */

public class GridListFragment extends BaseFragment
        implements RecyclerTClickListener<GridInfoDo> {

    @Bind(R.id.lineRight)
    LinearLayout lineRight;
    @Bind(R.id.txtClean)
    TextView txtClean;
    @Bind(R.id.editText)
    EditText editText;
    @Bind(R.id.empty_image)
    ImageView emptyImage;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

    private Gson gson = new Gson();
    private RecordGridListAdapter mRecordGridListAdapter;
    private List<GridInfoDo> mGridList = new ArrayList<>();
    private String searchParams = "";
    private String businessType = "";

    public static GridListFragment newInstance() {

        Bundle args = new Bundle();

        GridListFragment fragment = new GridListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static GridListFragment newInstance(String type) {

        Bundle args = new Bundle();
        args.putString(KeyConstants.KEY_BUSINESS_TYPE, type);

        GridListFragment fragment = new GridListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void getBaseArguments() {

        Bundle bundle = getArguments();

        if (bundle != null) {
            if (bundle.containsKey(KeyConstants.KEY_BUSINESS_TYPE)) {
                businessType = (String) bundle.getSerializable(KeyConstants.KEY_BUSINESS_TYPE);
            }
        }

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_grid_list;
    }

    @Override
    protected void initViews() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getmContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        mRecordGridListAdapter = new RecordGridListAdapter(mGridList, this);
        recyclerView.setAdapter(mRecordGridListAdapter);

        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == KeyEvent.ACTION_DOWN || actionId == EditorInfo.IME_ACTION_DONE) {
                    searchParams = editText.getText().toString().trim();
                    query();
                }
                return true;
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                searchParams = s.toString().trim();

                query();

                if (!"".equals(s.toString())) {
                    txtClean.setVisibility(View.VISIBLE);
                } else {
                    txtClean.setVisibility(View.GONE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        initData();
        getGridData();
    }

    /**
     * 获取网格数据
     */
    private void getGridData() {
        LemonRequestParams params = new LemonRequestParams("");
        RecordServices
                .init()
                .getGridList(params);
    }

    /**
     * 数据初始化
     */
    private void initData() {
        getSearchHistory();
    }

    @OnClick({R.id.lineRight, R.id.txtClean})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.lineRight:
                query();
                break;
            case R.id.txtClean:
                editText.getText().clear();
                break;
            default:
                break;
        }
    }

    /**
     * 清除历史记录的Ui事件
     *
     * @param event
     */
    @Subscribe
    public void onViewEvent(ViewEvent event) {

        if (RecordGridListAdapter.class.getName().equals(event.getTag())) {
            RecordUtils.removeGridSearchHistory(AccountUtil.getUserID());
            getSearchHistory();
        }
    }

    /**
     * 数据请求事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_GRID_BY_NAME.equals(event.getTag())) {
            // 获取网格点信息列表
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {

                mHUDUtil.showHUD();

            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow() && recyclerView != null) {

                mHUDUtil.hidden();

                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    List<GridInfoDo> list = (List<GridInfoDo>) event.getObj();
                    RecordUtils.saveGridData(AccountUtil.getUserID(), gson.toJson(list));

                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });

                }
            }
        }
    }

    /**
     * 发起搜索
     */
    private void query() {

        if ("".equals(searchParams)) {
            // 当搜索内容为空时，显示历史纪录
            getSearchHistory();
        } else {
            // 当搜索内容不为空时，匹配搜索结果
            containGridList(searchParams);
        }
    }

    /**
     * 点击网格点，跳转企业信息栏
     *
     * @param data
     * @param position
     */
    @Override
    public void onItemClick(GridInfoDo data, int position) {
        saveSearchHistory(data);

        if (CommonBo.BusinessType.HIDDEN_JUMP_SEARCH.getValue().equals(businessType)) {
            AppService.getBus().post(new DataEvent<GridInfoDo>(data, GridListFragment.class.getName()));
            AppManager.getAppManager().finishActivity(SafeHiddenDangerSearchActivity.class);
        } else {
            Bundle bundle = new Bundle();
            bundle.putSerializable(KeyConstants.KEY_GRID_DO, data);
            UIHelper.showActivity(getmContext(), bundle, RecordCompanyListActivity.class);
        }
    }


    /**
     * 匹配搜索关键词是否有这个网格点
     *
     * @param keyWord
     */
    private void containGridList(String keyWord) {

        String datas = RecordUtils.getGridData(AccountUtil.getUserID());

        if (datas != null) {

            List<GridInfoDo> gridInfoDos = gson.fromJson(datas, new TypeToken<List<GridInfoDo>>() {
            }.getType());

            mGridList.clear();

            for (GridInfoDo gridInfoDo : gridInfoDos) {
                if (gridInfoDo.getGrid_name().contains(keyWord)) {
                    mGridList.add(gridInfoDo);
                }
            }

            if (!mGridList.isEmpty()) {
                // 匹配到的网格信息不为空时
                emptyImage.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
                mRecordGridListAdapter.notifyDataSetChanged();
            } else {
                // 匹配到的网格信息为空时
                emptyImage.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
                emptyImage.setImageResource(R.mipmap.not_find_bg_grid);
            }

        } else {
            // 当本地没有获取到网格点信息时
            emptyImage.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            emptyImage.setImageResource(R.mipmap.not_find_bg_grid);
        }
    }

    /**
     * 获取搜索历史
     */
    private void getSearchHistory() {

        String history = RecordUtils.getGridSearchHistory(AccountUtil.getUserID());

        if (history != null) {
            //本地搜索历史不为空
            List<GridInfoDo> gridInfoDos;
            emptyImage.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            gridInfoDos = gson.fromJson(history, new TypeToken<List<GridInfoDo>>() {
            }.getType());

            mGridList.clear();
            GridInfoDo gridInfoDo = new GridInfoDo(); //历史纪录
            gridInfoDo.setView_type(SafeCloudConstants.VIEW_TYPE);
            gridInfoDo.setGrid_name(SafeCloudConstants.HISTORY_NAME);
            mGridList.addAll(gridInfoDos);
            mGridList.add(0, gridInfoDo);
            mRecordGridListAdapter.notifyDataSetChanged();

        } else {
            //本地搜索历史为空
            emptyImage.setVisibility(View.VISIBLE);
            emptyImage.setImageResource(R.mipmap.empty_bg_grid);
            recyclerView.setVisibility(View.GONE);
        }

    }

    /**
     * 保存搜索历史
     *
     * @param gridInfoDo
     */
    private void saveSearchHistory(GridInfoDo gridInfoDo) {

        String history = RecordUtils.getGridSearchHistory(AccountUtil.getUserID());
        List<GridInfoDo> gridInfoDos = new ArrayList<>();

        if (history != null) {

            gridInfoDos = gson.fromJson(history, new TypeToken<List<GridInfoDo>>() {
            }.getType());

            if (!gridInfoDos.contains(gridInfoDo)) {
                // 本次搜索记录为不存在，就保存

                if(gridInfoDos.size() >= Constants.HISTORY_MAX_NUMBER) {
                    int count = gridInfoDos.size() - Constants.HISTORY_MAX_NUMBER;
                    for(int i = 0; i <= count; i++) {
                        gridInfoDos.remove(gridInfoDos.size() - 1);
                    }
                    gridInfoDos.add(0, gridInfoDo);
                } else {
                    gridInfoDos.add(0, gridInfoDo);
                }
                RecordUtils.saveGridSearchHistory(AccountUtil.getUserID(), gson.toJson(gridInfoDos));
            }

        } else {
            // 本地历史为空时，直接保存搜索记录
            gridInfoDos.add(gridInfoDo);
            RecordUtils.saveGridSearchHistory(AccountUtil.getUserID(), gson.toJson(gridInfoDos));
        }

    }

}
